package com.wbs.rest.config;

import com.wbs.rest.executor.SqlExecutor;
import com.wbs.rest.handler.SqlModelHandler;
import com.wbs.rest.model.SqlModel;
import com.wbs.rest.model.SqlModelResolver;
import org.springframework.context.ApplicationContext;
import org.springframework.core.annotation.AnnotationAwareOrderComparator;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class SqlRestContext {

    SqlConfig sqlConfig;

    SqlModelResolver sqlModelResolver;

    SqlExecutor sqlExecutor;

    private List<SqlModelHandler> sqlModelHandlerList = new ArrayList<>();


    public SqlRestContext(SqlConfig sqlConfig, SqlModelResolver sqlModelResolver, SqlExecutor sqlExecutor) {
        this.sqlConfig = sqlConfig;
        this.sqlModelResolver = sqlModelResolver;
        this.sqlExecutor = sqlExecutor;

        reloadMapping();
    }

    public SqlModelResolver getSqlModelResolver() {
        return sqlModelResolver;
    }

    public SqlExecutor getSqlExecutor() {
        return sqlExecutor;
    }


    public void initSqlModelHandler(ApplicationContext applicationContext){
        sqlModelHandlerList = new ArrayList<>(applicationContext.getBeansOfType(SqlModelHandler.class).values());
        AnnotationAwareOrderComparator.sort(sqlModelHandlerList);
    }

    public List<SqlModelHandler> getSqlModelHandlerList() {
        return sqlModelHandlerList;
    }


    public void reloadMapping(){
        sqlModelResolver.loadMapping();
    }

    public Collection select(String uri, Object[] args) {
        return sqlExecutor.select(buildModel(uri, args));
    }

    public int insert(String uri, Object[] args) {
        return sqlExecutor.insert(buildModel(uri, args));
    }

    public int update(String uri, Object[] args) {
        return sqlExecutor.update(buildModel(uri, args));
    }

    public int delete(String uri, Object[] args) {
        return sqlExecutor.delete(buildModel(uri, args));
    }

    private SqlModel buildModel(String uri, Object[] args) {
        SqlModel sqlModel = new SqlModel();
        this.sqlModelResolver.resolveCommonProperties(sqlConfig.getBaseUri() + "/" + uri, sqlModel);
        sqlModel.setArgs(args);
        return sqlModel;
    }

}
